package com.pikachu.web.aop;

import com.pikachu.common.annotion.Permission;
import lombok.extern.log4j.Log4j2;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * 权限aop 根据注解检查
 * @author huang_kangjie
 * @create 2018-08-29 22:19
 **/
@Aspect
@Component
@Log4j2
public class PermissionAop {

     @Autowired
     private  HttpServletRequest request;
     @Autowired
     private StringRedisTemplate redisTemplate;

     @Pointcut(value = "@annotation(com.pikachu.common.annotion.Permission)")
     private void cutPermission() {

     }

     @Around("cutPermission()")
     public Object doPermission(ProceedingJoinPoint point) throws Throwable {
          MethodSignature ms = (MethodSignature) point.getSignature();
          Method method = ms.getMethod();
          Permission permission = method.getAnnotation(Permission.class);
          String token = "";
          try {
                token = this.request.getHeader("_tk");
               if(StringUtils.isEmpty(token)) {
                    log.debug("请求头必须带token");
                    //throw new IllegalArgumentException("请求头必须带token");
               }
          } catch (Exception e) {
               throw new Exception("验证权限时，获取请求头中token出错");
          }
          if(this.redisTemplate.hasKey(token)) {
               //TODO 验证权限
               Object[] permissions = permission.value();
               if (permissions != null && permissions.length > 0) {
                    //检查全体角色
                    boolean result = true;
                    if (result) {
                         return point.proceed();
                    } else {
                         return point.proceed();
                         //throw new BizException(BaseErrorCodeEnum.NO_AUTH_ERROR);
                    }
               } else {
                    return point.proceed();
                    //throw new BizException(BaseErrorCodeEnum.NO_PERMISSION_ERROR);
               }
          } else {
               //TODO 重新登录
               //暂时放过去
               return point.proceed();
               //throw new BizException(BaseErrorCodeEnum.NOT_FUND_TOKEN_ERROR);
          }

     }
}
